package com.example.zhinongbao.provider;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;

public class ZhinongbaoProvider extends ContentProvider {
    private static final String TAG = "ZhinongbaoProvider";

    // URI匹配码
    private static final int PRODUCTS = 1;
    private static final int PRODUCT_ID = 2;
    private static final int FOOTPRINTS = 3; // 足迹表匹配码
    private static final int FOOTPRINT_ID = 4; // 新增足迹ID匹配码
    private static final int MESSAGES = 10;
    private static final int MESSAGE_ID = 11;

    private static final int ORDERS = 100;
    private static final int ORDER_ID = 101;

    private static final int FRIEND_CIRCLE = 200;
    private static final int FRIEND_CIRCLE_ID = 201;
    private static final int USER_FOLLOW = 300;
    private static final int USER_FOLLOW_ID = 301;
    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        // 产品表URI
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.Products.TABLE_NAME, PRODUCTS);
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.Products.TABLE_NAME + "/#", PRODUCT_ID);

        // ========= 新增足迹表URI匹配 ========= [8,9](@ref)
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.FootprintEntry.TABLE_NAME, FOOTPRINTS);
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.FootprintEntry.TABLE_NAME + "/#", FOOTPRINT_ID);

        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.FriendCircle.TABLE_NAME, FRIEND_CIRCLE);
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.FriendCircle.TABLE_NAME + "/#", FRIEND_CIRCLE_ID);

        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.UserFollow.TABLE_NAME, USER_FOLLOW);
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.UserFollow.TABLE_NAME + "/#", USER_FOLLOW_ID);
        // 消息表URI
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.Messages.TABLE_NAME, MESSAGES);
        sUriMatcher.addURI(ZhinongbaoContract.AUTHORITY, ZhinongbaoContract.Messages.TABLE_NAME + "/#", MESSAGE_ID);
    }

    private SQLiteOpenHelper mDbHelper;




    @Override
    public boolean onCreate() {
        mDbHelper = new ZhinongbaoDbHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        Cursor cursor;
        String tableName;

        switch (sUriMatcher.match(uri)) {
            case PRODUCTS:
                tableName = ZhinongbaoContract.Products.TABLE_NAME;
                break;
            case PRODUCT_ID:
                tableName = ZhinongbaoContract.Products.TABLE_NAME;
                selection = ZhinongbaoContract.Products._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;

            case FRIEND_CIRCLE:
                tableName = ZhinongbaoContract.FriendCircle.TABLE_NAME;
                break;
            case FRIEND_CIRCLE_ID:
                tableName = ZhinongbaoContract.FriendCircle.TABLE_NAME;
                selection = ZhinongbaoContract.FriendCircle._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            // ========= 足迹表查询 ========= [8,9](@ref)
            case FOOTPRINTS:
                tableName = ZhinongbaoContract.FootprintEntry.TABLE_NAME;
                break;
            case FOOTPRINT_ID:
                tableName = ZhinongbaoContract.FootprintEntry.TABLE_NAME;
                selection = ZhinongbaoContract.FootprintEntry._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case USER_FOLLOW:
                tableName = ZhinongbaoContract.UserFollow.TABLE_NAME;
                break;
            case USER_FOLLOW_ID:
                tableName = ZhinongbaoContract.UserFollow.TABLE_NAME;
                selection = ZhinongbaoContract.UserFollow._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case MESSAGES:
                tableName = ZhinongbaoContract.Messages.TABLE_NAME;
                break;
            case MESSAGE_ID:
                tableName = ZhinongbaoContract.Messages.TABLE_NAME;
                selection = ZhinongbaoContract.Messages._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        cursor = db.query(
                tableName,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                sortOrder
        );

        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case PRODUCTS:
                return "vnd.android.cursor.dir/" + ZhinongbaoContract.AUTHORITY + "." + ZhinongbaoContract.Products.TABLE_NAME;
            case PRODUCT_ID:
                return "vnd.android.cursor.item/" + ZhinongbaoContract.AUTHORITY + "." + ZhinongbaoContract.Products.TABLE_NAME;

            // ========= 足迹表MIME类型 ========= [8](@ref)
            case FOOTPRINTS:
                return "vnd.android.cursor.dir/" + ZhinongbaoContract.AUTHORITY + "." + ZhinongbaoContract.FootprintEntry.TABLE_NAME;
            case FOOTPRINT_ID:
                return "vnd.android.cursor.item/" + ZhinongbaoContract.AUTHORITY + "." + ZhinongbaoContract.FootprintEntry.TABLE_NAME;
            case FRIEND_CIRCLE:
                return ZhinongbaoContract.FriendCircle.CONTENT_TYPE;
            case FRIEND_CIRCLE_ID:
                return ZhinongbaoContract.FriendCircle.CONTENT_ITEM_TYPE;
            // === 新增：用户关注表 ===
            case USER_FOLLOW:
                return ZhinongbaoContract.UserFollow.CONTENT_TYPE;
            case USER_FOLLOW_ID:
                return ZhinongbaoContract.UserFollow.CONTENT_ITEM_TYPE;
            case MESSAGES:
                return ZhinongbaoContract.Messages.CONTENT_TYPE;
            case MESSAGE_ID:
                return ZhinongbaoContract.Messages.CONTENT_ITEM_TYPE;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        long id;
        Uri contentUri;

        switch (sUriMatcher.match(uri)) {
            case PRODUCTS:
                id = db.insert(ZhinongbaoContract.Products.TABLE_NAME, null, values);
                contentUri = ZhinongbaoContract.Products.CONTENT_URI;
                break;

            // ========= 足迹表插入 ========= [9](@ref)
            case FOOTPRINTS:
                id = db.insert(ZhinongbaoContract.FootprintEntry.TABLE_NAME, null, values);
                contentUri = ZhinongbaoContract.FootprintEntry.CONTENT_URI;
                break;
            case FRIEND_CIRCLE:
                if (!values.containsKey(ZhinongbaoContract.FriendCircle.COLUMN_CREATE_TIME)) {
                    values.put(ZhinongbaoContract.FriendCircle.COLUMN_CREATE_TIME, System.currentTimeMillis() / 1000);
                }
                contentUri = ZhinongbaoContract.FriendCircle.CONTENT_URI;
                id = db.insert(ZhinongbaoContract.FriendCircle.TABLE_NAME, null, values);
                break;
            case USER_FOLLOW:
                id = db.insert(ZhinongbaoContract.UserFollow.TABLE_NAME, null, values);
                contentUri = ZhinongbaoContract.UserFollow.CONTENT_URI;
                break;
            case MESSAGES:
                id = db.insert(ZhinongbaoContract.Messages.TABLE_NAME, null, values);
                contentUri = ZhinongbaoContract.Messages.CONTENT_URI;
                break;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        if (id > 0) {
            Uri newUri = Uri.withAppendedPath(contentUri, String.valueOf(id));
            getContext().getContentResolver().notifyChange(newUri, null);
            notifyDependentUris(uri);
            return newUri;
        } else {
            Log.e(TAG, "Failed to insert row into " + uri);
            return null;
        }
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        int rowsDeleted;
        String tableName;

        switch (sUriMatcher.match(uri)) {
            case PRODUCTS:
                tableName = ZhinongbaoContract.Products.TABLE_NAME;
                break;
            case PRODUCT_ID:
                tableName = ZhinongbaoContract.Products.TABLE_NAME;
                selection = ZhinongbaoContract.Products._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;

            // ========= 足迹表删除 ========= [9](@ref)
            case FOOTPRINTS:
                tableName = ZhinongbaoContract.FootprintEntry.TABLE_NAME;
                break;
            case FOOTPRINT_ID:
                tableName = ZhinongbaoContract.FootprintEntry.TABLE_NAME;
                selection = ZhinongbaoContract.FootprintEntry._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case FRIEND_CIRCLE:
                tableName = ZhinongbaoContract.FriendCircle.TABLE_NAME;
                break;
            case FRIEND_CIRCLE_ID:
                tableName = ZhinongbaoContract.FriendCircle.TABLE_NAME;
                selection = ZhinongbaoContract.FriendCircle._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case USER_FOLLOW:
                tableName = ZhinongbaoContract.UserFollow.TABLE_NAME;
                break;
            case USER_FOLLOW_ID:
                tableName = ZhinongbaoContract.UserFollow.TABLE_NAME;
                selection = ZhinongbaoContract.UserFollow._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case MESSAGES:
                tableName = ZhinongbaoContract.Messages.TABLE_NAME;
                break;
            case MESSAGE_ID:
                tableName = ZhinongbaoContract.Messages.TABLE_NAME;
                selection = ZhinongbaoContract.Messages._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        rowsDeleted = db.delete(tableName, selection, selectionArgs);

        if (rowsDeleted > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return rowsDeleted;
    }

    private void notifyDependentUris(Uri operationUri) {
        ContentResolver resolver = getContext().getContentResolver();

        // 农友圈插入需要通知关注列表更新
        if (sUriMatcher.match(operationUri) == FRIEND_CIRCLE) {
            resolver.notifyChange(ZhinongbaoContract.UserFollow.CONTENT_URI, null);
        }

        // 添加其他关联通知...
    }
    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        int rowsUpdated;
        String tableName;

        switch (sUriMatcher.match(uri)) {
            case PRODUCTS:
                tableName = ZhinongbaoContract.Products.TABLE_NAME;
                break;
            case PRODUCT_ID:
                tableName = ZhinongbaoContract.Products.TABLE_NAME;
                selection = ZhinongbaoContract.Products._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;

            // ========= 足迹表更新 ========= [9](@ref)
            case FOOTPRINTS:
                tableName = ZhinongbaoContract.FootprintEntry.TABLE_NAME;
                break;
            case FOOTPRINT_ID:
                tableName = ZhinongbaoContract.FootprintEntry.TABLE_NAME;
                selection = ZhinongbaoContract.FootprintEntry._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case FRIEND_CIRCLE:
                tableName = ZhinongbaoContract.FriendCircle.TABLE_NAME;
                break;
            case FRIEND_CIRCLE_ID:
                tableName = ZhinongbaoContract.FriendCircle.TABLE_NAME;
                selection = ZhinongbaoContract.FriendCircle._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case USER_FOLLOW:
                tableName = ZhinongbaoContract.UserFollow.TABLE_NAME;
                break;
            case USER_FOLLOW_ID:
                tableName = ZhinongbaoContract.UserFollow.TABLE_NAME;
                selection = ZhinongbaoContract.UserFollow._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;
            case MESSAGES:
                tableName = ZhinongbaoContract.Messages.TABLE_NAME;
                break;
            case MESSAGE_ID:
                tableName = ZhinongbaoContract.Messages.TABLE_NAME;
                selection = ZhinongbaoContract.Messages._ID + "=?";
                selectionArgs = new String[]{String.valueOf(uri.getLastPathSegment())};
                break;

            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        rowsUpdated = db.update(tableName, values, selection, selectionArgs);

        if (rowsUpdated > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return rowsUpdated;
    }
}